<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="isUpdate ? t('common.edit') : t('common.create')"
      @register="register"
      @ok="handleSubmit"
      @cancel="clearForm"
      :destroyOnClose="true"
      :minHeight="400"
      :width="1000"
    >
      <Tabs v-model:activeKey="activeKey">
        <TabPane key="1" :tab="t('routes.demo.partManagerSettings.Property')">
          <Form :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }">
            <FormItem v-for="item in formItemsList" :key="item.prop" :label="item.label">
              <Input
                v-model:value="item.value"
                v-if="item.type === 'text'"
                :readonly="isUpdate"
                :disabled="
                  (!isUpdate && item.prop === 'id') ||
                  item.prop === 'ThitObjectId' ||
                  item.prop === 'version' ||
                  item.prop === 'status' ||
                  item.prop === 'type' ||
                  item.prop === 'creater' ||
                  item.prop === 'createtime'
                "
              />
            </FormItem>
          </Form>
        </TabPane>
        <TabPane key="2" :tab="t('routes.demo.partManagerSettings.Attachment')">
          <BasicTable @register="registerAttachmentTable">
            <template #toolbar>
              <a-button type="primary" @click="CreatePartDetailAttachment">
                {{ t('routes.demo.partManager.partDetailModal.addAttachment') }}
              </a-button>
              <a-button type="primary" @click="CreateCommonMap">
                {{ t('routes.demo.partManager.partDetailModal.createSharedFigureDoc') }}
              </a-button>
            </template>
            <!-- 操作 -->
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    icon: 'ant-design:delete-outlined',
                    color: 'error',
                    popConfirm: {
                      title: t('common.confirmDelete'),
                      confirm: DeletePartDetailAttachment.bind(null, record),
                    },
                  },
                ]"
              />
            </template>
          </BasicTable>
        </TabPane>
        <TabPane key="3" :tab="t('routes.demo.partManagerSettings.Associated')">
          <BasicTable @register="registerAssociatedTable">
            <template #toolbar>
              <a-button type="primary" @click="CreateAssociated">
                {{ t('common.create') }}
              </a-button>
            </template>
            <!-- 操作 -->
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    icon: 'ant-design:delete-outlined',
                    color: 'error',
                    popConfirm: {
                      title: t('common.confirmDelete'),
                      confirm: DeleteAssociated.bind(null, record),
                    },
                  },
                ]"
              />
            </template>
          </BasicTable>
        </TabPane>
      </Tabs>
    </BasicModal>
    <!-- 附件类型 -->
    <PartDetailAttachment @register="registerAttachmentType" @addPart="addPart" />
    <!-- 共图 -->
    <partModal @register="registerCommonMap" @addCommonMap="addCommonMap" />
    <!-- 关联 -->
    <partAssign @register="registerPartAssign" @addAssociated="addAssociated" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, inject, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { Form, FormItem, Tabs, TabPane, Input } from 'ant-design-vue';
  import {
    getPartAttr,
    AddPartAndFile,
    UploadPartFile,
    DeletePartFile,
    GetPartDetail,
    UpdatePart,
  } from '/@/api/demo/partManager';

  import { getPartDetailAttachmentColumns, getPartAssociatedColumns } from './tableData';

  import PartDetailAttachment from './PartDetailAttachment.vue';
  import partModal from './partModal.vue';
  import partAssign from './partAssign.vue';

  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  const isUpdate = ref(false);
  const activeKey = ref('1');
  // 附件列表
  const PartDetailAttachmentList = ref([]);
  const upLoadFileTypeList = ref([]);
  // 关联列表
  const PartAssociatedList = ref([]);
  const partGl = ref([]);
  // 共图列表
  const CommonMapList = ref([]);
  const partGt = ref([]);
  // 属性表单列表
  const formItemsList = ref([]);
  const FolderId = ref('');
  const partType = ref('');
  // 附件上传列表
  const files = ref<any>(null);

  const parent: any = inject('reload');

  // 提交
  async function handleSubmit() {
    formItemsList.value.map((item) => {
      if (item.prop === 'status' && item.value === '检出') {
        item.value = '2';
      }
    });
    const params = {
      partType: partType.value,
      folderId: FolderId.value,
      upLoadFileTypeList: upLoadFileTypeList.value,
      aboutIdList: partGt.value,
      docToDocList: partGl.value,
      addPropList: formItemsList.value,
    };
    setModalProps({ confirmLoading: true });
    try {
      if (unref(isUpdate)) {
        UpdatePart(params).then((res) => {
          if (res) {
            parent.handleReload();
            createMessage.success(t('common.successText'));
            clearForm();
          }
        });
      } else {
        AddPartAndFile(params).then((res) => {
          if (res) {
            parent.handleReload();
            createMessage.success(t('common.successText'));
            clearForm();
          }
        });
      }
    } finally {
      setModalProps({ confirmLoading: false });
      clearForm();
    }
  }

  const clearForm = () => {
    formItemsList.value = [];
    files.value = [];
    PartDetailAttachmentList.value = [];
    upLoadFileTypeList.value = [];
    CommonMapList.value = [];
    partGt.value = [];
    PartAssociatedList.value = [];
    partGl.value = [];
    activeKey.value = '1';
    closeModal();
  };

  // 新增附件
  const addPart = (data, file) => {
    const isExist = PartDetailAttachmentList.value.some((item) => item.fileName === data.fileName);
    if (isExist) {
      createMessage.error(t('routes.demo.partManager.partDetailModal.attachmentExist'));
    } else {
      const newData = new FormData();
      newData.append('file', file);
      UploadPartFile(newData).then((res) => {
        if (res) {
          PartDetailAttachmentList.value.push(data);
          upLoadFileTypeList.value.push(data);
          createMessage.success(t('common.uploadSuccess'));
        }
      });
    }
  };
  const CreatePartDetailAttachment = () => {
    openAttachmentTypeModal(true, { FolderId: FolderId.value });
  };

  // 删除附件
  const DeletePartDetailAttachment = (record) => {
    DeletePartFile(record.fileName).then((res) => {
      if (res) {
        PartDetailAttachmentList.value = PartDetailAttachmentList.value.filter(
          (item) => item.fileName !== record.fileName,
        );
        upLoadFileTypeList.value = upLoadFileTypeList.value.filter(
          (item) => item.fileName !== record.fileName,
        );
        CommonMapList.value = CommonMapList.value.filter((item) => item.name !== record.fileName);
        partGt.value = partGt.value.filter((item) => item !== record.id);
        createMessage.success(t('common.delSuccessText'));
      }
    });
  };

  // 新增共图
  const addCommonMap = (data) => {
    console.log(data);
    if (data.fileorpart !== '0') {
      createMessage.warning(t('routes.demo.partManager.partDetailModal.fileType'));
    } else if (data.state !== '8') {
      createMessage.warning(t('routes.demo.partManager.partDetailModal.status'));
    } else {
      const isExist = CommonMapList.value.some((item) => item.id === data.id);
      if (isExist) {
        createMessage.error(t('routes.demo.partManager.partDetailModal.sharedFigureDocExist'));
      } else {
        CommonMapList.value.push(data);
        partGt.value.push(data.id);
        // 附件和共图展示用的是一个表格
        let allData = {
          fileName: data.name,
          docType: data.type,
        };
        PartDetailAttachmentList.value.push(allData);
      }
    }
  };

  const CreateCommonMap = () => {
    openCommonMapModal(true, { isWhat: '共图' });
  };

  // 新增关联
  const addAssociated = (data) => {
    const isExist = PartAssociatedList.value.some((item) => item.id === data.id);
    if (isExist) {
      createMessage.error(t('routes.demo.partManager.partDetailModal.associated'));
    } else {
      PartAssociatedList.value.push(data);
      partGl.value.push(data.id);
    }
  };

  const CreateAssociated = () => {
    openAssociatedModal(true);
  };

  // 获取零件属性
  async function getPartAttrList() {
    const res = await getPartAttr(partType.value);
    res.forEach((element) => {
      if (element.prop === 'status' && element.value === '2') {
        element.value = '检出';
      }
    }),
      (formItemsList.value = res);
  }

  // 删除关联
  const DeleteAssociated = (data) => {
    PartAssociatedList.value = PartAssociatedList.value.filter((item) => item.id !== data.id);
    partGl.value = partGl.value.filter((item) => item !== data.id);
  };

  // 定义弹窗是否可见
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      // 修改
      let id = data.currentRecord.id;
      let version = data.currentRecord.version;
      GetPartDetail(id, version).then((res) => {
        res.addPropList.forEach((element) => {
          if (element.prop === 'status' && element.value === '2') {
            element.value = '检出';
          }
        });
        let newArr = [];
        res.faList.map((item) => {
          let newItem = {
            fileName: item.fileName,
            docType: item.fileType,
          };
          newArr.push(newItem);
        });
        // 关联数据
        let newDoc = [];
        res.docToDocList === null
          ? []
          : res.docToDocList.map((item) => {
              let newItem = {
                name: item.thitObjectId,
                version: item.version,
                filename: item.fileName,
                type: item.fileType,
                creator: item.creater,
              };
              newDoc.push(newItem);
            });
        partGt.value = res.faList.map((item) => item.fileId);
        partGl.value = res.docToDocList === null ? [] : res.docToDocList.map((item) => item.oId);
        formItemsList.value = res.addPropList;
        PartDetailAttachmentList.value = newArr;
        PartAssociatedList.value = newDoc;
        FolderId.value = data.FolderId;
        partType.value = data.partType;
      });
    } else {
      // 新增
      FolderId.value = data.FolderId;
      partType.value = data.partType;
      getPartAttrList();
    }
  });

  // 附件表格初始化
  const [registerAttachmentTable] = useTable({
    columns: getPartDetailAttachmentColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    canResize: false,
    dataSource: PartDetailAttachmentList,
    rowKey: 'key',
    actionColumn: {
      width: 200,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 关联表格初始化
  const [registerAssociatedTable] = useTable({
    columns: getPartAssociatedColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    canResize: false,
    rowKey: 'id',
    dataSource: PartAssociatedList,
    actionColumn: {
      width: 200,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 附件类型
  const [registerAttachmentType, { openModal: openAttachmentTypeModal }] = useModal();
  // 共图
  const [registerCommonMap, { openModal: openCommonMapModal }] = useModal();
  // 关联
  const [registerPartAssign, { openModal: openAssociatedModal }] = useModal();
</script>

<style lang="less" scoped></style>
